package com.zhijiang.common.util;


import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class WxService {
    public static final String TOKEN="lcc";
    //微信公众号
    private static final String GET_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static final String APPID="wx784482365eb95c84";
    private static final String APPSECRET="cdb5225910f64a62e9fef9897e333659";

    private static AccessToken at;

    //获取内部使用的token，私有的，不对外
    private static void getToken() {
        String url=GET_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        String tokenStr=Util.get(url);
        System.out.println("私有方法获取的accesstoken："+tokenStr);
        JSONObject jsonObject= JSONObject.parseObject(tokenStr);
        String token=jsonObject.getString("access_token");
        String expiresIn=jsonObject.getString("expires_in");
        at=new AccessToken(token, expiresIn);
        System.out.println("是否过期："+at.isExpired()+"/过期时间："+at.getExpireTime()+"/当前时间："+System.currentTimeMillis()+"/时间差："+(at.getExpireTime()-System.currentTimeMillis()));
    }
    //向外暴露的获取accesstoken方法
    public static String getAccessToken() {
        if(at==null || at.isExpired()) {
            getToken();
        }
        System.out.println(at.getAccessToken());
        return at.getAccessToken();

    }

    public static boolean check(String timestamp,String nonce,String signature) {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[] { TOKEN, timestamp, nonce };
        Arrays.sort(arr);
        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        String str=arr[0]+arr[1]+arr[2];
        String mysig=sha1(str);
        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        //System.out.println(mysig);
        //System.out.println(signature);
        return mysig.equalsIgnoreCase(signature);
    }


    private static String sha1(String src) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行 sha1 加密
            byte[] digest = md.digest(src.toString().getBytes());
            char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            StringBuilder sb=new StringBuilder();
            for(byte b:digest) {
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    //获取用户信息
    public static String getUserInfo(String openId) {
        String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        url=url.replace("ACCESS_TOKEN", WxService.getAccessToken()).replace("OPENID",openId );
        String result=Util.get(url);
        return result;
    }

}
